<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="queryForm.query"
        class="input-with-select"
        placeholder="请输入内容"
        @keyup.enter.native="handleSearch"
      >
        <el-select
          style="width: 128px"
          v-model="select"
          slot="prepend"
          placeholder="请选择"
        >
          <el-option label="用户名" value="1"></el-option>
          <!-- <el-option label="手机号" value="2"></el-option>
          <el-option label="邮箱" value="3"></el-option>
          <el-option label="个人说明" value="4"></el-option>
          <el-option label="学校名称" value="5"></el-option>
          <el-option label="状态" value="7"></el-option>
          <el-option label="备注" value="8"></el-option> -->
        </el-select>
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"
          >搜索</el-button
        >
      </el-input>
      <el-input
        v-model="queryForm.size"
        type="number"
        placeholder="请输入每页显示条数"
        @keyup.enter.native="handleSearch"
      >
        <template slot="prepend">每页数量</template>
      </el-input>
    </div>
    <!-- 搜索栏end -->
    <!-- 操作按钮 -->
    <div style="margin-top: 20px">
      <el-button type="primary" @click="handleAdd">添加</el-button>
      <el-button
        type="danger"
        @click="handleDisable()"
        v-show="selectedIds.length > 0"
        >批量封禁</el-button
      >
    </div>
    <!-- 操作按钮end -->
    <!-- 用户表单 -->
    <el-form>
      <el-table
        style="width: 100%; margin: 20px"
        :data="tableData"
        @select-all="handleSelectAll"
        @select="handleSelect"
      >
        <el-table-column fixed type="selection" width="55" />
        <el-table-column fixed="left" prop="userName" label="用户名" />
        <el-table-column prop="avatarPath" label="头像">
          <template slot-scope="scope">
            <el-image
              style="width: 50px; height: 50px"
              :src="downloadURL + scope.row.avatarPath"
              :fit="'contain'"
              :preview-src-list="previewList()"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="phoneNumber" label="手机号" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="userTypeId" label="用户类型">
          <template slot-scope="scope">
            <el-tag>{{ userTypeName(scope.row.userTypeId) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="stateTypeId" label="状态">
          <template slot-scope="scope">
            <el-tag :type="stateTypeTag(scope.row.stateTypeId)">{{
              stateTypeName(scope.row.stateTypeId)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="lastLoginDate" label="最后登录时间" />
        <el-table-column prop="createdDate" label="创建时间" />
        <el-table-column fixed="right" label="操作" width="256px">
          <template slot-scope="scope">
            <div class="df">
              <el-button
                type="primary"
                size="mini"
                @click="handleEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="warning"
                size="mini"
                @click="handleBindUserTypes(scope.row)"
                >角色绑定</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="handleDisable(scope.row)"
                >封禁</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <!-- 用户表单end -->
    <!-- 分页 -->
    <el-pagination
      background
      layout="prev, pager, next"
      :page-size="parseInt(page.size)"
      :page-count="parseInt(page.count)"
      :total="page.total"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
    <!-- 分页end -->
    <!-- 添加/编辑用户弹窗 -->
    <el-dialog
      :title="userForm.title"
      :visible.sync="editUserFormVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="userForm" :rules="rules" ref="userForm">
        <el-form-item label="头像" prop="avatarPath">
          <el-upload
            class="avatar-uploader"
            :headers="headers"
            :action="uploadURL"
            accept="image/*"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="SuccessUpload"
            :auto-upload="true"
          >
            <img
              class="avatar"
              v-if="userForm.avatarPath"
              :src="downloadURL + userForm.avatarPath"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="userForm.userName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input
            v-model="userForm.phoneNumber"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="userForm.handle === 'add'"
          label="密码"
          prop="password"
        >
          <el-input
            v-model="userForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="个人说明">
          <el-input
            v-model="userForm.statement"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="学校名称">
          <el-input
            v-model="userForm.schoolName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
            v-model="userForm.birthday"
            type="date"
            value-format="yyyy-MM-ddTHH:mm:ss"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="userForm.genderTypeId" placeholder="请选择">
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="(item, index) in genderList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select v-model="userForm.userTypeId" placeholder="请选择">
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="(item, index) in userTypeList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="userForm.stateTypeId" placeholder="请选择">
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="(item, index) in stateTypeList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="userForm.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editUserFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit('userForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 添加/编辑用户弹窗end -->
    <!-- 角色绑定弹窗 -->
    <el-dialog
      title="角色绑定"
      :visible.sync="bindUserTypesFormVisible"
      :close-on-click-modal="false"
    >
      <el-transfer
        v-model="transfer.value"
        :data="transfer.data"
        :titles="['未选角色', '已选角色']"
        :props="{
          key: 'id',
          label: 'name',
        }"
        filterable
        filter-placeholder="请输入内容"
      >
      </el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bindUserTypesFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleBindUserTypesSubmit()"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 角色绑定弹窗end -->
  </div>
</template>

<script>
import { getGenderTypeList } from "@/api/genderType";
import { getStateTypeList } from "@/api/stateType";
import { getUserTypeList } from "@/api/userType";
import { addUser,editUser,getUserList,banUser,bindUserTypes } from "@/api/user";
import { MD5Encrypt } from '@/utils/'

export default {
  data() {
    return {
      // 搜索多选索引
      select: "1",
      // 多选数据的Ids
      selectedIds: [],
      // 搜索框数据
      queryForm: {
        page: 1,
        size: 10,
        query: "",
      },
      // 分页数据
      page: {
        count: 1,
        size: 10,
        total: 0,
      },
      // 表单数据
      tableData: [],
      // 选项数据
      genderList: [],
      userTypeList: [],
      stateTypeList: [],
      // 添加用户数据(默认)，用于覆盖
      addUserForm: {
        id: 0,
        remark: "",
        avatarPath: "",
        userName: "",
        phoneNumber: "",
        email: "",
        password: "",
        statement: "",
        schoolName: "",
        birthday: null,
        genderTypeId: null,
        userTypeId: null,
        userTypeCodes: [],
        stateTypeId: null,
        handle: "add",
        title: "添加用户",
      },
      // 编辑用户数据
      userForm: {
        id: 0,
        remark: "",
        avatarPath: "",
        userName: "",
        phoneNumber: "",
        email: "",
        password: "",
        statement: "",
        schoolName: "",
        birthday: null,
        genderTypeId: null,
        userTypeId: null,
        userTypeCodes: [],
        stateTypeId: null,
        handle: "edit",
        title: "编辑用户",
      },
      // 添加/编辑表单显示
      editUserFormVisible: false,
      // 表单验证
      rules: {
        userName: {
          required: true,
          message: "请输入用户名",
          trigger: "blur",
        },
        phoneNumber: {
          required: true,
          message: "请输入手机号",
          trigger: "blur",
        },
        password: {
          required: true,
          message: "请输入密码",
          trigger: "blur",
        },
        email: {
          required: true,
          message: "请输入邮箱",
          trigger: "blur",
        },
      },
      // 请求头
      headers: {
        Authorization: "Bearer " + this.$store.getters.token,
      },
      // 上传下载地址
      uploadURL: process.env.VUE_APP_BASE_UPLOAD_API,
      downloadURL: process.env.VUE_APP_BASE_DOWNLOAD_API,
      // 穿梭框
      transfer: {
        userId: 0,
        // 选中的数据
        value: [],
        // 数据源
        data: [],
      },
      // 绑定用户类型表单显示
      bindUserTypesFormVisible: false,
    };
  },
  created() {
    console.log("headers:", this.headers);
    console.log("uploadURL:", this.uploadURL);
    console.log("downloadURL:", this.downloadURL);
    this.getGenderTypeList();
    this.getUserTypeList();
    this.getStateTypeList();
    this.handleSearch();
  },
  methods: {
    // 搜索操作
    handleSearch() {
      this.queryForm.page = 1;
      this.getUserList();
    },
    // 添加操作
    handleAdd() {
      this.userForm = Object.assign({}, this.addUserForm);
      this.handleDialog();
    },
    // 封禁操作
    handleDisable(param) {
      if (param === undefined) {
        const ids = this.selectedIds;
        if (ids.length === 0) {
          this.$message({
            type: "error",
            message: "请选择要封禁的用户",
          });
        } else {
          this.handleDisableConfirm()
            .then(() => {
              this.banUser({ ids });
            })
            .catch(() => {});
        }
      } else {
        this.handleDisableConfirm()
          .then(() => {
            this.banUser(param);
          })
          .catch(() => {});
      }
    },
    // 封禁提示
    handleDisableConfirm() {
      return this.$confirm("确定封禁吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
    },
    // 全选操作
    handleSelectAll(selection) {
      this.selectedIds = selection.map((item) => item.id);
    },
    // 选择操作
    handleSelect(selection) {
      this.selectedIds = selection.map((item) => item.id);
    },
    // 编辑操作
    handleEdit(row) {
      this.userForm = Object.assign({}, row);
      this.userForm.handle = "edit";
      this.userForm.title = "编辑用户";
      this.handleDialog();
    },
    // 绑定角色操作
    handleBindUserTypes(user) {
      // 获取用户列表中拥有"角色代码数组"
      // 需要根据"角色代码数组"去转成"id数组",进而绑定到穿梭框的value中
      var userTypeIds = user.userTypeCodes.map((code) => {
        const result = this.userTypeList.find((item) => item.code === code);
        return result ? result.id : null;
      });
      this.transfer.userId = user.id;
      this.transfer.value = userTypeIds;
      this.handleBindUserTypesDialog();
    },
    // 改变页数操作
    handleCurrentChange(val) {
      this.queryForm.page = val;
      this.getUserList();
    },
    // 对话框显示操作-添加/编辑用户表单
    handleDialog() {
      this.editUserFormVisible = !this.editUserFormVisible;
    },
    // 确认操作-添加/编辑用户表单
    handleSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.userForm.handle === "add") {
            this.addUser();
          } else if (this.userForm.handle === "edit") {
            this.editUser();
          }
        } else {
          this.$message.error("错误的提交");
        }
      });
    },
    // 上传头像之前
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 上传头像成功
    SuccessUpload(res, file) {
      this.userForm.avatarPath = res.data[0].fileName;
      console.log(res);
    },
    // 对话框显示操作-添加/编辑用户表单
    handleBindUserTypesDialog() {
      this.bindUserTypesFormVisible = !this.bindUserTypesFormVisible;
    },
    // 确认操作-角色绑定表单
    handleBindUserTypesSubmit() {
      console.log(this.transfer);
      const param = {
        id: this.transfer.userId,
        ids: this.transfer.value,
      };
      bindUserTypes(param).then((result) => {
        if (result.code === 200) {
          this.handleBindUserTypesDialog();
          this.getUserList();
          this.$message.success(result.message);
        }
      });
    },
    // 状态id转状态类型
    stateTypeTag(id) {
      if (this.stateTypeList.length > 0) {
        const item = this.stateTypeList.find(
          (item) =>
            item.id == id &&
            (item.name === "封禁" || item.name === "注销")
        );
        return item ? "danger" : "success";
      }
      return "";
    },
    // Id转角色名称
    userTypeName(id) {
      if (this.userTypeList.length > 0) {
        let item = this.userTypeList.find((item) => item.id === id);
        return item ? item.name : "";
      }
      return "";
    },
    // Id转状态名称
    stateTypeName(id) {
      if (this.stateTypeList.length > 0) {
        let item = this.stateTypeList.find((item) => item.id === id);
        return item ? item.name : "";
      }
      return "";
    },
    //头像预览路径
    previewList() {
      return this.tableData.map((item) => this.downloadURL + item.avatarPath);
    },
    // 获取性别列表
    getGenderTypeList() {
      let param = { page: 1, size: 99, query: "" };
      getGenderTypeList(param).then((result) => {
        if (result.code === 200) {
          this.genderList = result.data.list.map((item) => ({
            id: item.id,
            name: item.name,
          }));
          console.log("gender:", this.genderList);
        }
      });
    },
    // 获取角色列表
    getUserTypeList() {
      let param = { page: 1, size: 99, query: "" };
      getUserTypeList(param).then((result) => {
        if (result.code === 200) {
          this.userTypeList = result.data.list.map((item) => ({
            id: item.id,
            name: item.name,
            code: item.code,
          }));
          // 给穿梭框提供数据源
          this.transfer.data = this.userTypeList;
          console.log("userTypes:", this.userTypeList);
        }
      });
    },
    // 获取状态列表
    getStateTypeList() {
      let param = { page: 1, size: 99, query: "" };
      getStateTypeList(param).then((result) => {
        if (result.code === 200) {
          this.stateTypeList = result.data.list.map((item) => ({
            id: item.id,
            name: item.name,
          }));
          console.log("stateType:", this.stateTypeList);
        }
      });
    },
    // 获取用户列表
    getUserList() {
      if (this.queryForm.size === "") {
        this.$message({
          type: "error",
          message: "请输入每页显示条数",
        });
      } else {
        console.log("搜索条件:", this.queryForm);
        getUserList(this.queryForm)
          .then((result) => {
            if (result.code === 200) {
              console.log("user:", result);
              this.tableData = result.data.list;
              this.page.size = this.queryForm.size;
              this.page.count = result.data.total / this.queryForm.size;
              this.page.total = result.data.total;
            }
          })
          .catch(() => {});
      }
    },
    // 添加用户
    addUser() {
      console.log(this.userForm);
      let param = Object.assign({}, this.userForm);
      param.password = MD5Encrypt(this.userForm.password);
      addUser(param)
        .then((result) => {
          if (result.code === 200) {
            this.$message.success(result.message);
            this.queryForm.query = "";
            this.queryForm.size = 10;
            this.handleDialog()
            this.getUserList();
          }
        })
        .catch(() => {});
    },
    // 封禁用户
    banUser(param) {
      banUser(param)
        .then((result) => {
          if (result.code === 200) {
            this.$message.success(result.message);
            this.getUserList();
            if (param.userTypeIds) {
              this.selectedIds = []
            }
          }
        })
        .catch(() => {});
    },
    // 更新用户
    editUser() {
      editUser(this.userForm)
        .then((result) => {
          if (result.code === 200) {
            this.$message.success(result.message);
            this.handleDialog()
            this.handleSearch();
          }
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  .search-bar {
    display: flex;
    margin-top: 15px;
    .input-with-select {
      margin-right: 20px;
    }
  }
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>